using UnityEngine;
using System.Collections;

public class SpriteAnimation : MonoBehaviour
{

    public int frames = 24;
    public int framesPerSecond = 10;
    public int rows = 1;

    private Vector2 m_size;
    private int m_currentRow;
    private Animations m_currentAnimation; // change back to private
    private PlatformerController platformerController;

    public enum Animations
    {
        IDLE = 1,
        WALK_LEFT = 2,
        WALK_RIGHT = 3
    }

    public int currentRow
    {
        set
        {
            m_currentRow = value;
        }
    }

    // Use this for initialization
    void Start()
    {
        this.frames = Mathf.Abs(this.frames);
        this.framesPerSecond = Mathf.Abs(this.framesPerSecond);
        this.rows = Mathf.Abs(this.rows);
        this.platformerController = this.gameObject.transform.parent.GetComponent<PlatformerController>();

        this.m_size = new Vector2(1.0f / this.frames, 1.0f / this.rows);

        this.m_currentAnimation = Animations.IDLE;
        this.m_currentRow = 1;
    }

    // Update is called once per frame
    void Update()
    {
        // return if we have nothing to do
        if (renderer.material.GetTexture("_MainTex") == null)
            return;

        Vector2 offset = new Vector2();
        Vector2 size = m_size;

        // calc the current frame index
        float index = Time.time * this.framesPerSecond;

        // u coord of the material
        int uIndex = (int)(index % this.frames);

        switch (this.m_currentAnimation)
        {
            case Animations.IDLE:
                if (this.platformerController.movement.wasWalkingRight)
                {

                    this.m_currentRow = 1;
                }
                else if (this.platformerController.movement.wasWalkingLeft)
                {

                    this.m_currentRow = 2;
                }

                uIndex = 0;

                break;
            case Animations.WALK_LEFT:
                this.m_currentRow = 2;

                break;
            case Animations.WALK_RIGHT:
                this.m_currentRow = 1;
                break;
        }

        // v coord of the material
        int vIndex = this.m_currentRow % this.rows;

        offset = new Vector2(
            uIndex * size.x,
            1.0f - size.y - vIndex * size.y);

        //       	Debug.Log(uIndex + " " + offset.x);

        renderer.material.SetTextureOffset("_MainTex", offset);
        renderer.material.SetTextureScale("_MainTex", size);
    }

    public void PlayWalkLeftAnimation()
    {
        this.m_currentAnimation = Animations.WALK_LEFT;
    }

    public void PlayWalkRightAnimation()
    {
        this.m_currentAnimation = Animations.WALK_RIGHT;
    }

    public void PlayIdleAnimation()
    {
        this.m_currentAnimation = Animations.IDLE;
    }
}
